package cn.iocoder.yudao.module.pickbook.service.classinfo;

import cn.iocoder.yudao.module.pickbook.dal.dataobject.classes.PickbookClassDO;
import cn.iocoder.yudao.module.pickbook.dal.dataobject.classmember.PickbookClassMemberDO;
import cn.iocoder.yudao.module.pickbook.dal.mysql.classes.PickbookClassMapper;
import cn.iocoder.yudao.module.pickbook.dal.mysql.classmember.PickbookClassMemberMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * 班级 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class PickbookClassServiceImpl implements PickbookClassService {

    @Resource
    private PickbookClassMapper classMapper;

    @Resource
    private PickbookClassMemberMapper classMemberMapper;

    @Override
    public PickbookClassDO createClass(String name, String description, Long teacherId) {
        // 生成班级口令
        String classCode = generateClassCode();
        
        // 创建班级
        PickbookClassDO classInfo = PickbookClassDO.builder()
                .name(name)
                .description(description)
                .teacherId(teacherId)
                .studentCount(0)
                .classCode(classCode)
                .coverUrl("") // 默认封面
                .status(1) // 正常状态
                .build();
        
        // 保存班级
        classMapper.insert(classInfo);
        
        // 添加教师为班级成员
        PickbookClassMemberDO member = PickbookClassMemberDO.builder()
                .classId(classInfo.getId())
                .userId(teacherId)
                .role("TEACHER")
                .status(1)
                .build();
        classMemberMapper.insert(member);
        
        log.info("班级创建成功，班级ID: {}, 班级名称: {}, 班级口令: {}", 
                classInfo.getId(), name, classCode);
        
        return classInfo;
    }

    @Override
    public PickbookClassDO joinClassByCode(String classCode, Long userId) {
        // 根据班级口令查找班级
        PickbookClassDO classInfo = classMapper.selectByClassCode(classCode);
        if (classInfo == null) {
            throw new RuntimeException("班级口令无效");
        }
        
        // 检查用户是否已经是班级成员
        PickbookClassMemberDO existingMember = classMemberMapper.selectByClassIdAndUserId(
                classInfo.getId(), userId);
        if (existingMember != null) {
            throw new RuntimeException("您已经是该班级成员");
        }
        
        // 添加用户为班级成员
        PickbookClassMemberDO member = PickbookClassMemberDO.builder()
                .classId(classInfo.getId())
                .userId(userId)
                .role("STUDENT")
                .status(1)
                .build();
        classMemberMapper.insert(member);
        
        // 更新班级学生数量
        classInfo.setStudentCount(classInfo.getStudentCount() + 1);
        classMapper.updateById(classInfo);
        
        log.info("用户加入班级成功，用户ID: {}, 班级ID: {}", userId, classInfo.getId());
        
        return classInfo;
    }

    @Override
    public List<PickbookClassDO> getUserClasses(Long userId) {
        return classMapper.selectByUserId(userId);
    }

    @Override
    public PickbookClassDO getClass(Long id) {
        return classMapper.selectById(id);
    }

    @Override
    public void updateClass(PickbookClassDO classInfo) {
        classMapper.updateById(classInfo);
        log.info("班级信息更新成功，班级ID: {}", classInfo.getId());
    }

    @Override
    public void deleteClass(Long id) {
        // 删除班级成员
        classMemberMapper.deleteByClassId(id);
        
        // 删除班级
        classMapper.deleteById(id);
        
        log.info("班级删除成功，班级ID: {}", id);
    }

    @Override
    public String generateClassCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        
        // 生成6位数字和字母组合的班级口令
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        for (int i = 0; i < 6; i++) {
            code.append(chars.charAt(random.nextInt(chars.length())));
        }
        
        return code.toString();
    }
} 